package route

import (
    "collecter/app/common/helper"
    "collecter/app/middleware"

	"fmt"
	"io"
	"os"
	"time"

	"github.com/gin-gonic/gin"
)

func InitRouter() *gin.Engine {
	runmode := helper.Configer.GetString("runmode")
	if "product" == runmode {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
		f, _ := os.Create(helper.LogFileName)
		gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
	}
	router := gin.New()

	router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// 你的自定义格式
		var body string
		if bd, err := io.ReadAll(param.Request.Body); err == nil {
			body = string(bd)
		}

		return fmt.Sprintf("[%s]%s - [%s] \" %s %s %d %s %s %s\"\n",
			param.Request.Proto,
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Request.Host+param.Path,
			param.StatusCode,
			param.Latency,
			body,
			param.ErrorMessage,
		)
	}))
	router.Use(gin.Recovery())
	router.Use(middleware.Common())

	router = regiterAdminRouter(router)
	router = registerApiRouter(router)

	return router
}
